package com.manpower.configuraion;

import com.manpower.common.BusinessException;
import com.manpower.common.RestResponse;
import com.manpower.constant.Constants;
import com.manpower.dao.dataobject.sys.SysLogDto;
import com.manpower.dao.mapper.SysLogDtoMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 全局异常处理类
 * @ClassName GlobalDefultExceptionHandler
 * @Author weiyong.wang
 * @Date 2020/8/17
 */

@ControllerAdvice
public class GlobalDefultExceptionHandler {

	private static Logger logger = LoggerFactory.getLogger(GlobalDefultExceptionHandler.class);

	@Autowired
	private SysLogDtoMapper logDao;

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public RestResponse defultExcepitonHandler(HttpServletRequest request, Exception e) {
		SysLogDto sysLog = new SysLogDto();
		sysLog.setLogType(Constants.LOGTYPE_SYSTEM); //系统日志
		sysLog.setLogModule("pc-error");
		sysLog.setLogIp(request.getRemoteAddr());
		sysLog.setDeleteStatus(Constants.DELETE_STATUS_NO);
		sysLog.setKeepTime(0);
		sysLog.setCreateUser(null);
		sysLog.setCreateTime(new Date());
		sysLog.setReservedField1(request.getMethod()); //请求方法
		sysLog.setReservedField2(request.getRequestURI());
		if(e instanceof BusinessException) {
			BusinessException businessException = (BusinessException)e;

			String businessMsg = businessException.getMsg();
			if(StringUtils.isNotBlank(businessMsg) && businessMsg.length()>2000){
				businessMsg = businessMsg.substring(0,1999);
			}
			sysLog.setReservedField3("business");
			sysLog.setLogInfo(businessMsg);
			logDao.insert(sysLog);

			logger.info(this.getClass()+"业务异常：{}",businessException.getMsg());
			return new RestResponse(businessException.getErrorCode(),businessException.getMsg());
		}

		e.printStackTrace();

		String errorMsg = e.getMessage();
		if(StringUtils.isNotBlank(errorMsg) && errorMsg.length()>2000){
			errorMsg = errorMsg.substring(0,1999);
		}
		sysLog.setReservedField3("system");
		sysLog.setLogInfo(errorMsg);
		logDao.insert(sysLog);

		return new RestResponse(500,"系统内部错误",e.getMessage());
	}
}
